package com.zy.garbage.interceptor;

import com.zy.garbage.enums.ResultEnum;
import com.zy.garbage.exception.CommonException;
import com.zy.garbage.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义拦截器
 * 继承HandlerInterceptorAdapter
 * <p>
 * preHandle：进入到控制器方法之前执行的内容
 * boolean：
 * true：可以继续执行控制器方法
 * false：拦截
 * postHandle：执行控制器方法之后执行的内容
 * afterCompletion：响应结束之前执行的内容
 * <p>
 * 1.简化获取token数据的代码编写
 * 统一的用户权限校验（是否登录）
 * 2.判断用户是否当前访问接口的权限
 */
@Component
public class JwtInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    JwtUtil jwtUtil;

    /**
     * 简化获取token数据的代码编写（判断是否登录）
     * <p>
     * 1.通过request获取请求token信息
     * 2.从token中解析获取claims
     * 3.将claims绑定到request域中
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

//      放行预检请求
        if (request.getMethod().equals("OPTIONS")) {
            return true;
        }

//      1.通过request获取请求token信息


        String authorizationrequest = request.getHeader("Authorization");
//        判断请求头信息是否为空，或者是否以Bearer开头

        if (!StringUtils.isEmpty(authorizationrequest) && authorizationrequest.startsWith("Bearer")) {
//            获取token数据
//            try {
            String token = authorizationrequest.replace("Bearer", "");

//            System.out.println(token);


//            3.解析token
            Claims claims = jwtUtil.parseJwt(token);
            if (claims != null) {
                request.setAttribute("user_token", token);
                request.setAttribute("user_claims", claims);

                return true;
            }
        }
        throw new CommonException(ResultEnum.NO_LOGIN);

//            } catch (CommonException e) {
//                e.printStackTrace();
//                response.sendError(400,"您还未登录");
//                return false;
//            }
//        }
//        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        super.afterCompletion(request, response, handler, ex);
    }
}
